package com.hxy.ssm.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxy.ssm.bean.Employee;
import com.hxy.ssm.bean.EmployeeExample;
import com.hxy.ssm.bean.R;
import com.hxy.ssm.bean.vo.EmployeeVo;
import com.hxy.ssm.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("employee")
public class EmployeeController {

    @Autowired
    public EmployeeService employeeService;

    @GetMapping("/emplist")
    public String list(){
        return "employee/list";
    }
    @PostMapping("/emplist")
    @ResponseBody
    public R emplist(@RequestBody(required = false) EmployeeVo employeeVo) throws JsonProcessingException, ParseException {
        PageHelper.startPage(employeeVo.getPage(),employeeVo.getLimit());
       //List<Employee> list=employeeService.findAllEmp();
      EmployeeExample employeeExample=new EmployeeExample();
       EmployeeExample.Criteria criteria=employeeExample.createCriteria();
      if(employeeVo.getFirstName()!=null&&!employeeVo.getFirstName().equals("")){
          criteria.andFirstNameLike("%"+employeeVo.getFirstName()+"%");
      }
       SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
       if(employeeVo.getStart()!=null&&!employeeVo.getStart().equals("")){
          Date parse=sdf.parse(employeeVo.getStart());
           criteria.andDateGreaterThanOrEqualTo(parse);
       }
        if(employeeVo.getEnd()!=null&&!employeeVo.getEnd().equals("")){
           Date parse=sdf.parse(employeeVo.getEnd());
            criteria.andDateGreaterThanOrEqualTo(parse);
        }
       List<Employee> list=employeeService.findAllEmp(employeeExample);
        PageInfo<Employee> pageInfo=new PageInfo<Employee>(list);
        R r=new R();
        r.setCode(0);
        r.setMsg("");
        r.setCount(pageInfo.getTotal());
        r.setData(pageInfo.getList());
        return r;
    }
    @PostMapping("/insert")
    @ResponseBody
    public String insert(@RequestBody Employee employee){
        int i=employeeService.insert(employee);
        return i > 0 ? "true":"false";
    }
    @PostMapping("/update")
    @ResponseBody
    public String update(@RequestBody Employee employee){
        int i=employeeService.update(employee);
        return i > 0 ? "true":"false";
    }
    @GetMapping("/del/{id}")
    @ResponseBody
    public String delById(@PathVariable(value = "id") Integer id){

        int i=employeeService.delById(id);
        return i > 0 ? "true":"false";
    }

}
